package cn.alm.springaialibaba.controller;

import com.alibaba.cloud.ai.dashscope.api.DashScopeImageApi;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.image.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.URI;
import java.net.URL;

@RestController
@RequestMapping("image")
public class ImageModelController {

    @Autowired
    private DashScopeImageModel imageModel;

    @RequestMapping("generate")
    public void generate(@RequestParam String question, HttpServletResponse response) {
        ImageOptions options = ImageOptionsBuilder.builder()
                .model(DashScopeImageApi.DEFAULT_IMAGE_MODEL)
                .N(1)
                .width(1024)
                .height(1024)
                .build();
        ImagePrompt imagePrompt = new ImagePrompt(question, options);
        ImageResponse call = imageModel.call(imagePrompt);
        String imageUrl = call.getResult().getOutput().getUrl();
        // 在浏览器中输出
        try {
            URL url = URI.create(imageUrl).toURL();
            InputStream inputStream = url.openStream();
            response.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
            response.getOutputStream().write(inputStream.readAllBytes());
            response.getOutputStream().flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
